package com.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MqttTestConnection {
    
    @Value("${spring.mqtt.hostUrl}")
    private String broker;
    
    @Value("${spring.mqtt.username}")
    private String username;
    
    @Value("${spring.mqtt.password}")
    private String password;
    
    @Value("${spring.mqtt.clientId}")
    private String clientId;
    
    @Value("${spring.mqtt.defaultTopic}")
    private String topic;
    
    public void testConnection() {
        try {
            MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setCleanSession(false);
            options.setConnectionTimeout(30);
            options.setKeepAliveInterval(60);
            options.setAutomaticReconnect(true);
            
            System.out.println("Connecting to broker: " + broker);
            client.connect(options);
            System.out.println("Connected");
            
            System.out.println("Subscribing to topic: " + topic);
            client.subscribe(topic, (topic, message) -> {
                System.out.println("Received message: " + new String(message.getPayload()));
            });
            System.out.println("Subscribed");
            
            // 保持连接30秒用于测试
            Thread.sleep(30000);
            
            client.disconnect();
            System.out.println("Disconnected");
            client.close();
            
        } catch (MqttException | InterruptedException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}